The Map
object in JavaScript holds key-value pairs and remembers the original insertion order of the
keys. Any value (both objects and primitive values) may be used as either a key or a value.
You can create a map using the Map
constructor:
const map = new Map([
['key1', 'value1'],
['key2', 'value2'],
['key3', 'value3']
]);
console.log(map); // Outputs: Map(3) { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }
You can add and delete elements from a map using the set()
and delete()
methods:
const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');
console.log(map); // Outputs: Map(2) { 'key1' => 'value1', 'key2' => 'value2' }
map.delete('key1');
console.log(map); // Outputs: Map(1) { 'key2' => 'value2' }
You can check if a map contains a specific key using the has()
method:
const map = new Map([['key1', 'value1'], ['key2', 'value2']]);
console.log(map.has('key1')); // Outputs: true
console.log(map.has('key3')); // Outputs: false
You can get the value associated with a specific key using the get()
method:
const map = new Map([['key1', 'value1'], ['key2', 'value2']]);
console.log(map.get('key1')); // Outputs: 'value1'
console.log(map.get('key3')); // Outputs: undefined
You can iterate over the elements of a map using the for...of
loop:
const map = new Map([['key1', 'value1'], ['key2', 'value2']]);
for (let [key, value] of map) {
console.log(key + ': ' + value);
}
// Outputs:
// key1: value1
// key2: value2
You can convert a map to an array using the Array.from()
method or the spread operator:
const map = new Map([['key1', 'value1'], ['key2', 'value2']]);
const array = Array.from(map);
console.log(array); // Outputs: [['key1', 'value1'], ['key2', 'value2']]
const array2 = [...map];
console.log(array2); // Outputs: [['key1', 'value1'], ['key2', 'value2']]
Maps support various operations like clearing all elements and getting the size of the map:
const map = new Map([['key1', 'value1'], ['key2', 'value2']]);
// Size
console.log(map.size); // Outputs: 2
// Clear
map.clear();
console.log(map); // Outputs: Map(0) {}